import java.lang.Math.*;
import java.util.ArrayList;

public class compute100msin implements Runnable
{
	public static int threadidx;
	public static final int threadnum = 20;
	public static float[] threadoutputdata;
	private int tidx;
	public compute100msin()
	{
		this.tidx = compute100msin.threadidx % compute100msin.threadnum;
		compute100msin.threadidx += 1;
	}
	public void run()
	{
		int cptnum = compute100msin.maxnum/threadnum;
		int offset = this.tidx*cptnum;
		System.out.println("in run tidx=" + this.tidx + " offset="+offset);
		int i;
		for(i=0; i<cptnum; ++i)
		{
			compute100msin.threadoutputdata[offset+i] = (float)(Math.sin(Math.sqrt(i+offset)));
		}
		System.out.println("in run tidx=" + this.tidx + " over");
	}

	public static final int maxnum = 100000000;
	public static void doComputeSingle(float[] outputdata )
	{
		int i;
		for(i=1; i<compute100msin.maxnum; ++i)
		{
			
			outputdata[i] = (float)(Math.sin(Math.sqrt(i)));
		}
	}

	public static void doComputeMultiThread(float[] outputdata)
	{
		compute100msin.threadidx=0;
		compute100msin.threadoutputdata = outputdata;
		int loop;
		ArrayList<Thread> threadlist = new ArrayList<Thread>();
		try
		{
			for(loop=0;loop<compute100msin.threadnum;++loop)
			{
				Thread tmpthread = new Thread(new compute100msin());
				tmpthread.start();
				threadlist.add(tmpthread);
			}
			for(loop=0;loop<compute100msin.threadnum;++loop)
			{
				Thread tmpthread = threadlist.get(loop);
				tmpthread.join();
			}
		}
		catch(InterruptedException e)
		{
			System.out.println("in doComputeMultiThread crash");
		}
		System.out.println("in doComputeMultiThread over");
	}
	
	public static void main(String[] args)
	{
		System.out.println("in compute100msin");

		long startTime=System.nanoTime();

		float[] outputdata = new float[compute100msin.maxnum];
		long memappTime=System.nanoTime();

		//doComputeSingle(outputdata);	
		doComputeMultiThread(outputdata);

		long endTime=System.nanoTime();

		System.out.println("memappTime="+((memappTime-startTime)/1000000)+"ms");
		System.out.println("costTime="+((endTime-startTime)/1000000)+"ms");
	}
}
